package drds.server.sqlparser.sqlobject;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import drds.server.sqlparser.visitor.Visitor;

/**
 * 
 * @author 曹正辉<330937205@qq.com>
 * 
 */
public abstract class AbstractSqlObject implements SqlObject {

	private SqlObject parent;

	protected Map<String, Object> attributeMap;

	public AbstractSqlObject() {
	}

	public final void accept(Visitor visitor) {
		if (visitor == null) {
			throw new IllegalArgumentException();
		}

		visitor.preVisit(this);

		accept0(visitor);

		visitor.postVisit(this);
	}

	protected abstract void accept0(Visitor visitor);

	protected final void acceptChild(Visitor visitor, List<? extends SqlObject> children) {
		if (children == null) {
			return;
		}

		for (SqlObject child : children) {
			acceptChild(visitor, child);
		}
	}

	protected final void acceptChild(Visitor visitor, SqlObject child) {
		if (child == null) {
			return;
		}

		child.accept(visitor);
	}

	public void output(StringBuffer sb) {
		sb.append(super.toString());
	}

	public String toString() {
		StringBuffer sb = new StringBuffer();
		output(sb);
		return sb.toString();
	}

	public void setParent(SqlObject parent) {
		this.parent = parent;
	}

	public SqlObject getParent() {
		return parent;
	}

	public void putAttribute(String name, Object value) {
		if (attributeMap == null) {
			attributeMap = new HashMap<String, Object>(1);
		}

		attributeMap.put(name, value);
	}

	public Object getAttribute(String name) {
		if (attributeMap == null) {
			return null;
		}

		return attributeMap.get(name);
	}

	public Map<String, Object> getAttributeMap() {
		if (attributeMap == null) {
			attributeMap = new HashMap<String, Object>(1);
		}

		return attributeMap;
	}

}
